package com.piesat.quake.business.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.piesat.quake.business.device.mapper.DStationDataMapper;
import com.piesat.quake.business.device.model.DeviceOptions;
import com.piesat.quake.business.device.model.config.Passageway;
import com.piesat.quake.business.device.model.config.StationAndThreshold;
import com.piesat.quake.business.device.model.config.StationData;
import com.piesat.quake.business.device.service.DPassagewayService;
import com.piesat.quake.business.device.service.DStationDataService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-03-13
 */
@Service
public class DStationDataServiceImpl extends ServiceImpl<DStationDataMapper, StationData> implements DStationDataService {
    @Autowired
    private DPassagewayService passagewayService;
    @Override
    public StationData getStationData(String id){
        return baseMapper.selectById(id);
    }

    @Override
    public List<Passageway> getPassageways(String id){
        QueryWrapper<Passageway> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id)
                .orderByAsc("passageway_id");
        return passagewayService.list(queryWrapper);
    }

    @Override
    public void saveDeviceConfig(DeviceOptions deviceOptions) {
        StationAndThreshold stationAndThreshold = deviceOptions.getStationAndThreshold();
        StationData stationData = stationAndThreshold.toStationData();
        List<Passageway> passagewayBlocks = new ArrayList<>(4);
        passagewayBlocks.add(deviceOptions.getPassageway1());
        passagewayBlocks.add(deviceOptions.getPassageway2());
        passagewayBlocks.add(deviceOptions.getPassageway3());
        passagewayBlocks.add(deviceOptions.getPassageway4());
        passagewayBlocks.add(deviceOptions.getPassageway5());
        passagewayBlocks.add(deviceOptions.getPassageway6());
        String id = deviceOptions.getId();
        passagewayService.updatePassageways(passagewayBlocks,id);
        boolean save = saveOrUpdate(stationData);
        if (!save){
            throw new IllegalStateException("写入站点数据异常");
        }
    }

    @Override
    public void update(StationData stationData) {
        boolean b = saveOrUpdate(stationData);
        if (!b){
            throw new IllegalStateException("更新设备参数失败");
        }
    }
}
